package com.zscat.mallplus.service.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zscat.mallplus.entity.dto.ConsultDto;
import com.zscat.mallplus.entity.dto.ReviewInformationDto;
import com.zscat.mallplus.entity.vo.oms.EvaluationCostmOrder;
import com.zscat.mallplus.entity.vo.oms.EvaluationOrder;
import com.zscat.mallplus.entity.vo.pms.PmsProductConsultInfoCastmVo;
import com.zscat.mallplus.entity.vo.pms.PmsProductConsultInfoVo;
import com.zscat.mallplus.oms.entity.OmsOrder;
import com.zscat.mallplus.oms.entity.OmsOrderItem;
import com.zscat.mallplus.oms.mapper.OmsOrderItemMapper;
import com.zscat.mallplus.oms.mapper.OmsOrderMapper;
import com.zscat.mallplus.pms.entity.*;
import com.zscat.mallplus.pms.mapper.*;
import com.zscat.mallplus.service.oms.service.IOmsEvaluateService;
import com.zscat.mallplus.service.pms.service.impl.PmsProductConsultServiceImpl;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.vo.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author ZuRongTang
 * @Date 2020/3/4
 **/

@Service
public class OmsEvaluateServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements IOmsEvaluateService {

    @Resource
    private OmsOrderMapper omsOrderMapper;

    @Resource
    private OmsOrderItemMapper omsOrderItemMapper;

    @Resource
    private PmsSkuStockMapper pmsSkuStockMapper;

    @Resource
    private PmsProductReplyMapper pmsProductReplyMapper;

    @Resource
    private PmsProductConsultMapper pmsProductConsultMapper;

    @Resource
    private PmsProductPraiseMapper pmsProductPraiseMapper;

    @Resource
    private PmsProductMapper pmsProductMapper;


    @Resource
    private PmsProductConsultServiceImpl pmsProductConsultService;

    @Resource
    private PmsProductConsultIntroductionMapper pmsProductConsultIntroductionMapper;


    //评价

    @Override
    public CommonResult completedSuccesOrders(Long memberId, String orderSn) {

        List<EvaluationOrder> result = new ArrayList<>();
        CommonResult commonResult = new CommonResult();

        OmsOrder omsOrder = findMemberIdOrder("member_id", memberId, "id", orderSn);

        if (omsOrder == null) {
            return commonResult.failed("该订单已不存在");
        }

        if (omsOrder.getIsComment() == 2) {
            return commonResult.failed("该订单已被评价");
        }

        Long id = omsOrder.getId();

        List<OmsOrderItem> omsOrderItems = findOrderGoods("order_id", id);

        if (omsOrderItems.size() == 0) {
            return commonResult.failed("无当前订单得商品信息");
        }

        //EvaluationOrder

        for (OmsOrderItem omsOrderItem : omsOrderItems) {
            EvaluationOrder evaluationOrder = new EvaluationOrder();

            evaluationOrder.setId(omsOrderItem.getId());
            evaluationOrder.setSkuId(omsOrderItem.getProductSkuId());
            evaluationOrder.setProductId(omsOrderItem.getProductId());
            evaluationOrder.setProductPic(omsOrderItem.getProductPic());
            evaluationOrder.setProductName(omsOrderItem.getProductName());
            evaluationOrder.setProductAttr(omsOrderItem.getProductAttr());
            evaluationOrder.setProductPrice(omsOrderItem.getProductPrice());

            result.add(evaluationOrder);
        }

        return commonResult.success(result);
    }

    @Override
    public PageInfo<PmsProductConsultInfoVo> getMyCompletedEvaluation(Long memberId, Integer pageIndex, Integer pageSize) {

        List<PmsProductConsult> member_id = findAllMyEvaluation("member_id", memberId);


        List<PmsProductConsult> consults = findMyEvaluate("member_id", memberId, pageIndex.longValue(), pageSize.longValue());

        List<PmsProductConsultInfoVo> result = new ArrayList<>();

        boolean flag = false;

        if (consults.size() > 0) {


            for (PmsProductConsult pmsProductConsult : consults) {

                PmsProductConsultInfoVo pmsProductConsultInfoVo = new PmsProductConsultInfoVo();

                Long skuId = pmsProductConsult.getSkuId();

                PmsSkuStock pmsSkuStock = pmsSkuStockMapper.selectById(skuId);

                if (pmsSkuStock != null) {
                    String pic = pmsSkuStock.getPic();

                    if (!StringUtils.isEmpty(pic)) {
                        pmsProductConsultInfoVo.setGoodsImg(pic);
                    } else {
                        pmsProductConsultInfoVo.setGoodsImg("");
                    }
                } else {
                    pmsProductConsultInfoVo.setGoodsImg("");
                }

                BeanUtils.copyProperties(pmsProductConsult, pmsProductConsultInfoVo);

                String images = pmsProductConsult.getImages();

                if (!StringUtils.isEmpty(images)) {
                    String[] split = images.split(",");
                    pmsProductConsultInfoVo.setImages(split);
                } else {
                    pmsProductConsultInfoVo.setImages(new String[0]);
                }

                Date consultAddtime = pmsProductConsult.getConsultAddtime();

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");

                pmsProductConsultInfoVo.setConsultAddtime(simpleDateFormat.format(consultAddtime));

//                if (pmsProductConsult.getIsanonymous()) {
//
//                    String memberName = pmsProductConsult.getMemberName();
//
//                    String[] split = memberName.split("");
//
//                    String name = split[0] + "*" + "*" + "*" + split[split.length - 1];
//
//                    pmsProductConsultInfoVo.setMemberName(name);
//                }

                PmsProductReply nodeConsult = findNodeConsult("reply_id", pmsProductConsult.getId(), "type", 1);

                List<PmsProductReply> pmsProductReplies = findNodeConsult("reply_id", pmsProductConsult.getId());


                if (nodeConsult != null) {
                    pmsProductConsultInfoVo.setTreasurer(nodeConsult.getContent());
                } else {
                    pmsProductConsultInfoVo.setTreasurer("");
                }

                PmsProductPraise memberPraise = findMemberPraise("reply_id", pmsProductConsult.getId(), "member_id", memberId);

                if (memberPraise != null) {
                    flag = true;
                }

                Boolean isanonymous = pmsProductConsult.getIsanonymous();
                pmsProductConsultInfoVo.setPrice(pmsSkuStock.getPrice());
                pmsProductConsultInfoVo.setCommentNumber(pmsProductReplies.size());
                pmsProductConsultInfoVo.setIsPraise(flag);
                pmsProductConsultInfoVo.setIsanonymous(isanonymous == true ? 0 : 1);
                result.add(pmsProductConsultInfoVo);
            }

        } else {
            return null;
        }

        return new PageInfo<>(member_id.size(), pageIndex, pageSize, result);
    }

    private List<PmsProductConsult> findAllMyEvaluation(String column, Object value) {
        QueryWrapper<PmsProductConsult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value);
        return pmsProductConsultMapper.selectList(queryWrapper);
    }

    @Override
    public PageInfo<EvaluationCostmOrder> getUndoneEvaluation(Long memberId, Integer pageIndex, Integer pageSize) {
        List<OmsOrder> memberIdOrderPage1 = findMemberIdOrderPage("member_id", memberId, "confirm_status", 1, "is_comment", 1);
        List<OmsOrder> memberIdOrderPage = findMemberIdOrderPage("member_id", memberId, "confirm_status", 1, "is_comment", 1, pageIndex.longValue(), pageSize.longValue());

        List<EvaluationCostmOrder> evaluationCostmOrders = new ArrayList<>();

        if (memberIdOrderPage.size() > 0) {

            for (OmsOrder omsOrder : memberIdOrderPage) {
                EvaluationCostmOrder evaluationCostmOrder = new EvaluationCostmOrder();
                evaluationCostmOrder.setId(omsOrder.getId());
                evaluationCostmOrder.setOrderSn(omsOrder.getOrderSn());
                List<OmsOrderItem> omsOrderItems = findOrderGoods("order_id", omsOrder.getId());
                List<EvaluationOrder> result = new ArrayList<>();
                for (OmsOrderItem omsOrderItem : omsOrderItems) {

                    EvaluationOrder evaluationOrder = new EvaluationOrder();

                    evaluationOrder.setId(omsOrderItem.getId());
                    evaluationOrder.setSkuId(omsOrderItem.getProductSkuId());
                    evaluationOrder.setProductId(omsOrderItem.getProductId());
                    evaluationOrder.setProductPic(omsOrderItem.getProductPic());
                    evaluationOrder.setProductName(omsOrderItem.getProductName());
                    evaluationOrder.setProductAttr(omsOrderItem.getProductAttr());
                    evaluationOrder.setProductPrice(omsOrderItem.getProductPrice());

                    result.add(evaluationOrder);
                }
                evaluationCostmOrder.setEvaluationOrders(result);

                evaluationCostmOrders.add(evaluationCostmOrder);
            }
        } else {
            return null;
        }

        return new PageInfo<>(memberIdOrderPage1.size(), pageIndex, pageSize, evaluationCostmOrders);
    }

    @Override
    public CommonResult setAnonymous(Long memberId, Long id) {
        String name = null;
        CommonResult commonResult = new CommonResult();
        PmsProductConsult myCousult = findMyCousult("id", id, "member_id", memberId);

        if (myCousult != null) {

            Boolean isanonymous = myCousult.getIsanonymous();
            String memberName = myCousult.getMemberName();
            if (isanonymous) {
                myCousult.setIsanonymous(false);

                String[] split = memberName.split("");
                name = split[0] + "*" + "*" + "*" + split[split.length - 1];
            } else {
                myCousult.setIsanonymous(true);
                name = memberName;
            }
            pmsProductConsultMapper.updateById(myCousult);
            return commonResult.success(name);
        } else {
            return commonResult.failed("未找到当前评论");
        }
    }

    @Override
    public CommonResult setCannotComment(Long memberId, Long id) {
        CommonResult commonResult = new CommonResult();
        PmsProductConsult myCousult = findMyCousult("id", id, "member_id", memberId);
        if (myCousult != null) {

            Integer commentStatus = myCousult.getCommentStatus();

            if (commentStatus == 0) {
                myCousult.setCommentStatus(1);
            } else {
                myCousult.setCommentStatus(0);
            }
            pmsProductConsultMapper.updateById(myCousult);
            return commonResult.success();
        } else {
            return commonResult.failed("未找到当前评论");
        }
    }

    @Override
    public CommonResult setHideComment(Long memberId, Long id) {
        CommonResult commonResult = new CommonResult();
        PmsProductConsult myCousult = findMyCousult("id", id, "member_id", memberId);
        if (myCousult != null) {

            Integer status = myCousult.getStatus();

            if (status == 0) {
                myCousult.setStatus(1);
            } else {
                myCousult.setStatus(0);
            }
            pmsProductConsultMapper.updateById(myCousult);
            return commonResult.success();
        } else {
            return commonResult.failed("未找到当前评论");
        }
    }

    @Override
    @Transactional
    public CommonResult addGoodsConsult(Long memberId, String name, ConsultDto consultDto) {
        CommonResult commonResult = new CommonResult();
        //压缩
        OmsOrder memberOrder = null;
        String compressionImg = null;


        Long orderId = consultDto.getOrderId();

        memberOrder = findMemberOrder("member_id", memberId, "id", orderId, "confirm_status", 1, "delete_status", 0, "is_comment", 1);

        if (memberOrder == null) {
            return commonResult.failedIsNull("评价得订单已不存在");
        }

        List<ReviewInformationDto> reviewInformation = consultDto.getReviewInformation();

        for (ReviewInformationDto reviewInformationDto : reviewInformation) {
            OmsOrderItem omsOrderItem = omsOrderItemMapper.selectById(reviewInformationDto.getId());
            String imgs = reviewInformationDto.getImgs();

            if (!StringUtils.isEmpty(imgs)) {
                String[] split = imgs.split(",");

                for (String fileName : split) {
                    String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);

                    if (fileExtName.contains("mp4")) {
                        continue;
                    }
                    compressionImg = pmsProductConsultService.fileUpload(fileName);
                    //不是视频地址,就取进行下载压缩
                }

            } else {
                //如果等于空,就去取商品得原始图片

                Long productId = omsOrderItem.getProductId();

                PmsProduct pmsProduct = pmsProductMapper.selectById(productId);

                String albumPics = pmsProduct.getAlbumPics();


                if (!StringUtils.isEmpty(albumPics)) {
                    String[] split = albumPics.split(",");

                    for (String fileName : split) {
                        String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);

                        if (fileExtName.contains("mp4")) {
                            continue;
                        }
                        compressionImg = pmsProductConsultService.fileUpload(fileName);
                    }
                }
            }

            PmsProductConsult pmsProductConsult = new PmsProductConsult();

            pmsProductConsult.setPraise(0L);
            pmsProductConsult.setMemberId(memberId);
            pmsProductConsult.setConsultAddtime(new Date());
            pmsProductConsult.setConsultContent(reviewInformationDto.getContent());
            pmsProductConsult.setStoreId(omsOrderItem.getStoreId());
            pmsProductConsult.setGoodsId(omsOrderItem.getProductId());
            pmsProductConsult.setSkuId(omsOrderItem.getProductSkuId());
            pmsProductConsult.setGoodsName(omsOrderItem.getProductName());
            pmsProductConsult.setIsanonymous(reviewInformationDto.getIsanonymous() == 1 ? true : false);
            pmsProductConsult.setPic(omsOrderItem.getProductPic());
            pmsProductConsult.setAttr(omsOrderItem.getProductAttr());
            pmsProductConsult.setStars(1);
            pmsProductConsult.setOrderId(omsOrderItem.getOrderId());
            pmsProductConsult.setType(1);
            pmsProductConsult.setImages(imgs);
            pmsProductConsult.setScore(reviewInformationDto.getScore());
            pmsProductConsult.setStatus(0);
            pmsProductConsult.setCommentStatus(0);
            pmsProductConsult.setShareImg("http://192.168.1.51:8085/file/"+compressionImg);
            pmsProductConsult.setMemberName(name);

            pmsProductConsultMapper.insert(pmsProductConsult);
        }
        memberOrder.setIsComment(2);
        omsOrderMapper.updateById(memberOrder);

        //修改订单评价状态

        return commonResult.success();

    }

    @Override
    public String getConsultIntroduction() {
        List<PmsProductConsultIntroduction> pmsProductConsultIntroductions = pmsProductConsultIntroductionMapper.selectList(null);
        return pmsProductConsultIntroductions.get(0).getContent();
    }

    private OmsOrder findMemberOrder(String column, Object value, String column1, Object value1, String
            column2, Object value2, String column3, Object value3, String column4, Object value4) {
        QueryWrapper<OmsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1).eq(column2, value2).eq(column3, value3).eq(column4, value4);
        return omsOrderMapper.selectOne(queryWrapper);
    }

    private PmsProductConsult findMyCousult(String column, Object value, String column1, Object value1) {
        QueryWrapper<PmsProductConsult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return pmsProductConsultMapper.selectOne(queryWrapper);
    }

    private List<PmsProductConsult> findMyEvaluate(String column, Object value, Long value1, Long value2) {
        QueryWrapper<PmsProductConsult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value);
        IPage<PmsProductConsult> page = new Page<>();

        page.setSize(value2);
        page.setCurrent(value1);

        return pmsProductConsultMapper.selectPage(page, queryWrapper).getRecords();
    }

    private List<OmsOrderItem> findOrderGoods(String column, Object value) {
        QueryWrapper<OmsOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value);
        return omsOrderItemMapper.selectList(queryWrapper);
    }

    private OmsOrderItem findOrderGood(String column, Object value) {
        QueryWrapper<OmsOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value);
        return omsOrderItemMapper.selectOne(queryWrapper);
    }


    private OmsOrder findMemberIdOrder(String column, Object value, String column1, Object value1) {
        QueryWrapper<OmsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return omsOrderMapper.selectOne(queryWrapper);
    }

    private List<OmsOrder> findMemberIdOrderPage(String column, Object value, String column1, Object value1, String
            column2, Object value2, Long value3, Long value4) {
        QueryWrapper<OmsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1).eq(column2, value2);
        IPage<OmsOrder> page = new Page<>();

        page.setCurrent(value3);
        page.setSize(value4);
        return omsOrderMapper.selectPage(page, queryWrapper).getRecords();
    }

    private List<OmsOrder> findMemberIdOrderPage(String column, Object value, String column1, Object value1, String
            column2, Object value2) {
        QueryWrapper<OmsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1).eq(column2, value2);
        return omsOrderMapper.selectList(queryWrapper);
    }


    private PmsProductReply findNodeConsult(String column, Object value, String column1, Object value1) {
        QueryWrapper<PmsProductReply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return pmsProductReplyMapper.selectOne(queryWrapper);
    }

    private List<PmsProductReply> findNodeConsult(String column, Object value) {
        QueryWrapper<PmsProductReply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value);
        return pmsProductReplyMapper.selectList(queryWrapper);
    }

    private PmsProductPraise findMemberPraise(String column, Object value, String column1, Object value1) {
        QueryWrapper<PmsProductPraise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return pmsProductPraiseMapper.selectOne(queryWrapper);
    }
}
